
/**
 * Created by  lizhihang
 */

'use strict';
var express = require('express');
var router = express.Router();
var logger = require('../logger');
var superagent = require('superagent');
var mongo = require('mongoskin');
var jwt = require('jsonwebtoken');
var db = mongo.db("mongodb://localhost:27017/weGDUT");
db.bind('weGDUT');


/**
 * Test Login
 *
 */
function send(req, res, next) {
  if (!req.query.code || !req.query.nickName || !req.query.avatarUrl) {
    res.send({ code: 401, message: 'code or nickName or avatarUrl is required' })
  }else{
    const code = req.query.code
    var name = req.query.nickName
    console.log(code)
    getUserInfoFromWechat(code).then(function (result) {
      result = JSON.parse(result)
      result.nickName = req.query.nickName   //用户昵称
      result.avatarUrl = req.query.avatarUrl //用户头像
      if (result.errcode) {
        res.send({ code: result.errcode, message: result.errmsg })   //code 非法
      } else {
        var re = new Promise((resolve, reject) => {
          db.weGDUT.find({ "openid": result.openid }).toArray(function (err, items) {
            resolve(items)
          })
        })
        var users
        re.then(function (value) {
          users = value[0]
          if (!users) {
            db.weGDUT.insert(result)
          }

          var token = jwt.sign(result, 'thefirstminappofvtmer');
          console.log(token)
          res.send({ code: 200, message: 'ok', data: token })
        })
      }
    }), function (error) {
      console.log(error)
    }
    }  
}


function getUserInfoFromWechat(code) {
  return new Promise((resolve, reject) => {
    var url = 'https://api.weixin.qq.com/sns/jscode2session?appid=wx45380ff8bc1c2e10&secret=87c693361e5cdfe9f5be081ac3bcd425&js_code=' + code + '&grant_type=authorization_code'
    superagent.get(url)
      .end(function (err, res) {
        if (err) {
          reject(err);
        };
        resolve(res.text);
      })
  })
}

module.exports = { send };
